<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增', 0)">新增</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedListIds)">
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', 1, scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', 2, scope.row)">编辑</el-button>
        <!-- <el-button type="primary" link :icon="Delete" @click="deleteItem(scope.row)">删除</el-button> -->
      </template>
    </ProTable>

    <!-- 弹窗相关 -->
    <el-drawer v-model="drawer" :title="drawerTitle" :direction="direction" :before-close="handleClose">
      <el-form ref="jsonForm" :model="jsonData" label-width="120px">
        <el-form-item label="类型">
          <el-select v-model="jsonData.type" disabled>
            <el-option label="品牌" value="brand"></el-option>
            <el-option label="型号" value="model"></el-option>
            <el-option label="系统类型" value="os_type"></el-option>
            <el-option label="系统型号" value="os_id"></el-option>
            <el-option label="位置" value="position"></el-option>
            <el-option label="设备状态" value="status"></el-option>
            <el-option label="采集点位" value="collection_point"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父级ID" v-if="isShowParent">
          <!-- <el-input v-model="jsonData.parent_id" placeholder="请输入父级ID"></el-input> -->

          <el-select v-model="jsonData.parent_id" placeholder="Select" size="large" style="width: 240px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="字段值">
          <el-input v-model="jsonData.value" placeholder="请输入字段值"></el-input>
        </el-form-item>
        <el-form-item label="字段说明">
          <el-input v-model="jsonData.remark" placeholder="请输入字段说明"></el-input>
        </el-form-item>
        <el-form-item label="解析方式">
          <el-select v-model="jsonData.data_format" placeholder="请选择">
            <el-option label="字符串" value="string"></el-option>
            <el-option label="JSON" value="json"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-if="isEdit != 1" type="primary" @click="confirm">确认</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 弹窗END -->
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted } from 'vue'
import { User } from '@/api/interface'
import type { DrawerProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProTable from '@/components/ProTable/index.vue'
const drawer = ref(false)
const drawerTitle = ref('')
const direction = ref<DrawerProps['direction']>('rtl')
const isEdit = ref(0) //0新增；1编辑；2查看
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
import { CirclePlus, Delete, EditPen, View } from '@element-plus/icons-vue'
import { getDeviceList, deleteDevice, addDevice, editDevice } from '@/api/modules/device'
import { defineProps } from 'vue'
const props = defineProps<{
  fieldType: string
}>()
const jsonData = reactive<Device.DeviceSettingsEdit>({
  id: 0,
  type: props.fieldType,
  parent_id: 0,
  value: '',
  remark: '',
  data_format: ''
})
const isShowParent = ref(false) //是否显示弹出框中的parentid输入库
if (props.fieldType == 'os_id' || props.fieldType == 'model') {
  isShowParent.value = true
}
const proTable = ref<ProTableInstance>()
const initParam = reactive({ type: 1 })
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.total,
    page: data.page,
    page_size: data.page_size
  }
}

const options = ref<{ value: string; label: string }[]>([])

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params))
  if (props.fieldType == 'os_id' || props.fieldType == 'model') {
    return getDeviceList({ ...newParams, type: props.fieldType, parent_id: 1 })
  } else {
    return getDeviceList({ ...newParams, type: props.fieldType })
  }
}

const getParentId = async () => {
  let ret: any

  if (props.fieldType == 'os_id') {
    ret = await getDeviceList({ page: 1, page_size: 1000, type: 'os_type' })
  }
  if (props.fieldType == 'model') {
    ret = await getDeviceList({ page: 1, page_size: 1000, type: 'brand' })
  }

  if (ret && ret.code === 0) {
    options.value = ret.data.data.map(item => ({
      value: item.id.toString(),
      label: item.value
    }))
  }
}

onMounted(() => {
  getParentId()
})
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { type: 'selection', fixed: 'left', width: 70 },
  {
    prop: 'parent_id',
    label: 'parent_id'
  },
  {
    prop: 'type',
    label: '类型'
  },
  {
    prop: 'value',
    label: 'value'
  },
  { prop: 'remark', label: 'remark' },
  { prop: 'data_format', label: 'data_format' },
  { prop: 'operation', label: '操作', fixed: 'right', width: 330 }
])

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  ElMessage.success('修改列表排序成功')
}

const openDrawer = (title: string, isEditVal: number, rowData?: any) => {
  drawer.value = true
  drawerTitle.value = title
  isEdit.value = isEditVal
  if (isEditVal == 0) {
    jsonData.type = props.fieldType
    jsonData.parent_id = 0
    jsonData.value = ''
    jsonData.remark = ''
    jsonData.data_format = ''
  } else if (rowData) {
    jsonData.id = rowData.id
    jsonData.type = props.fieldType
    jsonData.parent_id = 0
    jsonData.value = rowData.value
    jsonData.remark = rowData.remark
    jsonData.data_format = rowData.data_format
  }
}

const batchDelete = (ids: (string | number)[]) => {
  ElMessageBox.confirm(`此操作将永久删除id为${ids.join(',')}的数据, 是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

const deleteItem = async (rowData: Device.DeviceSettingsEdit) => {
  try {
    await ElMessageBox.confirm(`此操作将永久删除id为${rowData.id}的数据, 是否继续?`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 用户点击确认后，执行删除操作
    await deleteDevice({ id: rowData.id })
    ElMessage.success('删除成功')
    proTable.value?.getTableList()
  } catch (error) {
    console.log(error)
    // 用户取消删除或删除操作失败
    ElMessage.info('取消删除')
  }
}

const handleClose = (done: () => void) => {
  ElMessageBox.confirm('您确定要关闭此吗？')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

const confirm = async () => {
  try {
    if (isEdit.value == 2) {
      //编辑
      const res = await editDevice(jsonData as any)
    }
    if (isEdit.value == 0) {
      //新增
      const res = await addDevice(jsonData as any)
    }
    drawer.value = false
    proTable.value?.getTableList()
  } catch (error: any) {
    ElMessage.error(error)
  }
}

const cancel = () => {
  ElMessage.info('取消成功')
  drawer.value = false
}
// 文件下载
</script>
